<template>
  <div class="sortDropDown">
    <el-dropdown
      size="medium"
      type="primary"
      trigger="click"
      @command="handlerCommand($event)"
    >
      <span class="el-dropdown-link">
        {{ label }}<i class="el-icon-arrow-down el-icon--right"></i>
      </span>
      <el-dropdown-menu slot="dropdown">
        <el-dropdown-item
          v-for="item in dropdownItemList"
          :key="item.key"
          :command="item.key"
        >
          <el-dropdown-item>
            <i
              class="dropdown-icon"
              :class="item.sort ? (item.sort==='asc' ? 'el-icon-top' : 'el-icon-bottom') : ''"
            ></i>
            {{ item.name }}
          </el-dropdown-item>
        </el-dropdown-item>
      </el-dropdown-menu>
    </el-dropdown>
  </div>
</template>

<script lang='ts'>
import { DropdownOption, SortDropdownOption } from '@/models/form'
import { isEmpty, isNotEmpty } from '@/utils/validate'
import { Component, Vue, Emit, Prop } from 'vue-property-decorator'

@Component({})
export default class SortDropdown extends Vue {
  @Prop({ required: true }) dataList!: SortDropdownOption[];
  @Prop({ default: '排序' }) label!: string;
  @Prop({ default: false }) disabled!: boolean;

  get dropdownItemList() {
    return this.dataList.filter((item: SortDropdownOption) => isEmpty(item.permission) || (item.permission && this.$hasPermission(item.permission)))
  }

  private handlerCommand(key: string) {
    const item = this.dataList.find((item: SortDropdownOption) => item.key === key)
    if (!item) return
    if (item?.sort === 'desc') item.sort = 'asc'
    else if (item?.sort === 'asc') item.sort = 'desc'
    else {
      item.sort = 'asc'
      this.dataList.filter((item: SortDropdownOption) => item.key !== key).forEach((item: SortDropdownOption) => { item.sort = '' })
    }
    this.sortChange(item)
  }

  @Emit()
  sortChange(item: SortDropdownOption) {
    return item
  }
}
</script>

<style lang="scss" scoped>
  .dropdown-icon{
    width: 20px;
    display: inline-block;
  }
</style>
